﻿// ===================================
// <copyright file="StsDBLoggingProvider.cs" company="Shore Tech Systems LLP">Copyright (c) 12/06/2012 All Right Reserved</copyright>
// <author>Ross Buggins</author>
// <email>mailto:rbuggins@shoretechsystems.co.uk</email>
// <created>12/06/2012 15:07:03</created>
// <lastedit>12/06/2012 15:07:03</lastedit>
// <comments></comments>

// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.

// ===================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Xml;

using DotNetNuke.Common.Utilities;
using DotNetNuke.ComponentModel;
using DotNetNuke.Entities.Host;
using DotNetNuke.Framework;
using DotNetNuke.Instrumentation;
using DotNetNuke.Services.Scheduling;
using DotNetNuke.Services.Log;
using DotNetNuke.Services.Log.EventLog;
using DotNetNuke.Services.Log.EventLog.DBLoggingProvider;
using DotNetNuke.Services.Mail;

namespace Sts.Dnn.LoggingProvider
{
    /// <summary>
    /// This class extends the default Dnn logging provider to allow for better email notifications.
    /// 
    /// Note. There is currently a bug with Dnn and email notifications, see:
    /// http://support.dotnetnuke.com/issue/ViewIssue.aspx?ID=20424&PROJID=2
    /// 
    /// As a work around run this SQL command after changing an email notification settings:
    /// 
    /// update [dbo].[EventLogConfig] set [NotificationThresholdTimeType] = 1
    /// 
    /// </summary>
    public class StsDBLoggingProvider : DotNetNuke.Services.Log.EventLog.DBLoggingProvider.DBLoggingProvider
    {
        protected string lineBreak = "<br/>";
        protected int maxEventsPerEmail = 1;

        /// <summary>
        /// Sends the log notifications with some better formatting than Dnn uses by default.
        /// </summary>
        public override void SendLogNotifications()
        {
            List<LogTypeConfigInfo> configInfos = CBO.FillCollection<LogTypeConfigInfo>(DataProvider.Instance().GetEventLogPendingNotifConfig());
            foreach (LogTypeConfigInfo typeConfigInfo in configInfos)
            {
                string subject = string.Empty;

                IDataReader dr = DataProvider.Instance().GetEventLogPendingNotif(Convert.ToInt32(typeConfigInfo.ID));
                string log = "";
                try
                {
                    while (dr.Read())
                    {
                        LogInfo logInfo = FillLogInfo(dr);
                        subject += logInfo.LogTypeKey + " (" + logInfo.LogCreateDate + ") ";
                        log += logInfo.LogCreateDate.ToString();
                        log += lineBreak;
                        log += logInfo.LogTypeKey;
                        log += lineBreak;
                        log += logInfo.LogPortalName;
                        log += lineBreak;
                        log += lineBreak;
                        log += logInfo.Serialize() + lineBreak + lineBreak;
                    }
                }
                finally
                {
                    CBO.CloseDataReader(dr, true);
                }
                Mail.SendEmail(typeConfigInfo.MailFromAddress, typeConfigInfo.MailToAddress, "Event Notification " + subject, log);
                DataProvider.Instance().UpdateEventLogPendingNotif(Convert.ToInt32(typeConfigInfo.ID));
            }
        }

        public static IEnumerable<LogTypeConfigInfo> GetLogTypesWithPendingEmails()
        {
            IEnumerable<LogTypeConfigInfo> configInfos = CBO.FillCollection<LogTypeConfigInfo>(DataProvider.Instance().GetEventLogPendingNotifConfig());
            return configInfos;
        }

        public static void SendEmails(IDataReader dr)
        {
            var configs = GetLogTypesWithPendingEmails();
            foreach (var config in configs)
            {
                SendsEmailsForConfig(config);
            }
        }

        public static void SendsEmailsForConfig(LogTypeConfigInfo config)
        {

        }

        public static void AddToEmailOrSend(LogInfo logInfo, int currentCount, int maxPerEmail)
        {

        }

        public static void AddToCurrentEmail(LogInfo logInfo, string email)
        {

        }

        public static void SendEmail(string from, string to, string subject, string email)
        {

        }

        /// <summary>
        /// Fills the log info, unfortunately this is private on the base class, it should be protected really.
        /// </summary>
        /// <param name="dr">The dr.</param>
        /// <returns></returns>
        protected static LogInfo FillLogInfo(IDataReader dr)
        {
            var obj = new LogInfo();
            try
            {
                obj.LogCreateDate = Convert.ToDateTime(dr["LogCreateDate"]);
                obj.LogGUID = Convert.ToString(dr["LogGUID"]);
                if (dr["LogPortalID"] != DBNull.Value)
                {
                    obj.LogPortalID = Convert.ToInt32(dr["LogPortalID"]);
                }
                if (dr["LogPortalName"] != DBNull.Value)
                {
                    obj.LogPortalName = Convert.ToString(dr["LogPortalName"]);
                }
                if (dr["LogServerName"] != DBNull.Value)
                {
                    obj.LogServerName = Convert.ToString(dr["LogServerName"]);
                }
                if (dr["LogUserID"] != DBNull.Value)
                {
                    obj.LogUserID = Convert.ToInt32(dr["LogUserID"]);
                }
                obj.LogTypeKey = Convert.ToString(dr["LogTypeKey"]);
                obj.LogUserName = Convert.ToString(dr["LogUserName"]);
                obj.LogConfigID = Convert.ToString(dr["LogConfigID"]);
                obj.LogProperties.Deserialize(Convert.ToString(dr["LogProperties"]));
            }
            catch (Exception exc)
            {
                DnnLog.Error(exc);
            }
            return obj;
        }

    }
}
